package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpExprService empExprService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        boolean r = this.save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
        return r;
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = this.getById(id);
        if (emp==null){
            return null;
        }
        //查询工作经历
        List<EmpExpr> list = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id));
        emp.setExprList(list);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEmpById(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        boolean r = this.updateById(emp);
        //删除工作经历

        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //添加工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList!=null&&exprList.size()>0){
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);
        }
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeEmpsByIds(List<Integer> ids) {
        //批量删除员工
        boolean b = this.removeBatchByIds(ids);
        //批量删除员工工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
        return b;
    }
}
